package com.taldh.mutlithread.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class CountTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 2;  // 阈值

    private final int start;
    private final int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;

        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end ; i++) {
                sum = sum + i;
            }
        } else {
            int middle = (start + end) / 2;
            CountTask leftTask = new CountTask(start, middle);
            CountTask rightTask = new CountTask(middle+1, end);

//            ForkJoinTask<Integer> leftForkJoinTask = leftTask.fork();
//            ForkJoinTask<Integer> rightForkJoinTask = rightTask.fork();

//            int leftResult = leftForkJoinTask.join();
//            int rightResult = rightForkJoinTask.join();

            int leftResult = leftTask.invoke();
            int rightResult = rightTask.invoke();
            return leftResult + rightResult;
        }

        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        CountTask task = new CountTask(1,4);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        try {
            System.out.println("submit = " + submit.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
